package mwa.cs.sm.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.dao.ZoneDAO;
import mwa.cs.database.Database;
import mwa.cs.model.Zone;
import mwa.cs.util.JDate;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/**
 * Servlet implementation class CS0101003Svrl
 */
public class CS11003Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Database db;
	private int vnSiteId;
	private int vnUserId;
	private String vaUrlAddress;
	private String vaAgentBrowser;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CS11003Srvl() {
        super();
       }
    
    public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

    		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
    		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
			vaUrlAddress = request.getParameter("url_address");
			vaAgentBrowser = request.getParameter("agent_browser");
			vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
			String vaProcessType = request.getParameter("process_type");
			//System.out.println(process_type);
			if(vaProcessType.equals("insert")){ 
				insert(request,response);	
			} else if(vaProcessType.equals("edit")){ 
				edit(request , response);
			}else if(vaProcessType.equals("delete")){
				delete(request,response);
			}else if(vaProcessType.equals("update")) {
				update(request,response);
			}else{
				getDataTable(request,response);
			}
    	
    }
    
    public void getDataTable(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
				request.setCharacterEncoding("UTF-8");
				response.setCharacterEncoding("UTF-8"); 
				response.setContentType("text/JSON");		
				JSONObject voObject = new JSONObject();
				JSONArray voRow = new JSONArray();
				JSONArray voColumn = null;
				PrintWriter voOut = response.getWriter();
				
				this.db = new Database();
				
				ZoneDAO voZoneDAO = new ZoneDAO(db);
				
				List<Map<String , Object>> voListFindAll;

				voListFindAll = voZoneDAO.findZoneBySite(vnSiteId);
			
				for(int i = 0; i < voListFindAll.size() ; i++){ 
					Map<String , Object> mapItem = (Map<String , Object>) voListFindAll.get(i);
					voColumn = new JSONArray();
					voColumn.add(i+1);
					voColumn.add(mapItem.get("ZONE_ID"));
					voColumn.add(mapItem.get("ZONE_NAME"));
					voRow.add(voColumn);
				}
					voObject.put("iTotalRecords", voListFindAll.size());
					voObject.put("iTotalDisplayRecords", voListFindAll.size());
					voObject.put("aaData", voRow);
					db.close();
					voOut.print(voObject.toJSONString());
}
    
    public void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db = new Database();
		int pnZoneId = Integer.parseInt(request.getParameter("id"));
		int pnOldZoneID = Integer.parseInt(request.getParameter("oldZoneID"));
		
		String paZoneName = request.getParameter("desp");
		String vaDate = JDate.getDate();
		String vaTime = JDate.getTime();
		
		ZoneDAO voZoneDAO = new ZoneDAO(db);
		String vaCheckZoneId = voZoneDAO.findsZoneIdBySiteAndZoneId(vnSiteId,pnOldZoneID,pnZoneId);
		
		if(vaCheckZoneId == null){
			Zone poZone = new Zone();
			poZone.setVnSiteId(vnSiteId);
			poZone.setVnZoneId(pnZoneId);
			poZone.setVaZoneName(paZoneName);
			poZone.setVnUpdateUserId(vnUserId);
			poZone.setVaUpdateDate(vaDate);
			poZone.setVaUpdateTime(vaTime);

			try {
				db.beginTransaction();
				voZoneDAO.updateZone(vnSiteId, pnOldZoneID, poZone);
				db.commit();
			} catch (Exception e) {
				SMErrorLogDAO.getInstance().addLog(0, "CS11003", JDate.getDate(), JDate.getTime(),vnUserId, "CS11003Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
				db.rollback();
				e.getMessage();
			}finally{
				db.close();
			}
			response.getWriter().write("Success Data");
		
		}else{
			db.close();
			response.getWriter().write("ZoneID_Dupicate");
		}
		
	}
    public void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	
		
		this.db = new Database();
		int vnZoneId = Integer.parseInt(request.getParameter("id"));
		ZoneDAO voZoneDAO = new ZoneDAO(db);
		try {
			db.beginTransaction();
			voZoneDAO.deleteCustomerByAccount(vnSiteId, vnZoneId);
			db.commit();
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS11003", JDate.getDate(), JDate.getTime(),vnUserId, "CS11003Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
			e.getMessage();
		}finally{
			db.close();
		}
		
		response.getWriter().write("Success Data");
		
	}
    public void insert(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		
		this.db = new Database();
		
		int vnZoneId = Integer.parseInt(request.getParameter("id"));
		String vaZoneName = request.getParameter("desp");
		String vaDate = JDate.getDate();
		String vaTime = JDate.getTime();
		ZoneDAO voZoneDAO = new ZoneDAO(db);
		String vaCheckZoneId = voZoneDAO.findZoneIdBySiteAndZoneId(vnSiteId, vnZoneId);
		
		if(vaCheckZoneId == null){
			
			Zone poZone = new Zone();
			poZone.setVnSiteId(vnSiteId);
			poZone.setVnZoneId(vnZoneId);
			poZone.setVaZoneName(vaZoneName);
			poZone.setVnInsertUserId(vnUserId);
			poZone.setVaInsertDate(vaDate);
			poZone.setVaInsertTime(vaTime);
			
			ZoneDAO voZonesDAO = new ZoneDAO(db);
			try {
				db.beginTransaction();
				voZonesDAO.addZone(poZone);
				db.commit();
			} catch (Exception e) {
				SMErrorLogDAO.getInstance().addLog(0, "CS11003", JDate.getDate(), JDate.getTime(),vnUserId, "CS11003Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
				db.rollback();
				e.getMessage();
			}finally{
				db.close();
			}
			response.getWriter().write("Success Data");
			
		}else{
			db.close();
			response.getWriter().write("ZoneID_Dupicate");
		}
	}

    public void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		
		
		this.db  = new Database();
		int vnZoneId = Integer.parseInt(request.getParameter("id"));
		
		
		ZoneDAO  voZoneDAO  = new ZoneDAO(this.db);
		//daoZoneDAO.findZoneNameBySiteAndZoneId(vnSiteId, pnZoneId);
		
		
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("id" , vnZoneId);
		jsonObject.put("desp", voZoneDAO.findZoneNameBySiteAndZoneId(vnSiteId, vnZoneId));
		
		//System.out.println(" data ;  " + daoZoneDAO.findZoneNameBySiteAndZoneId(vnSiteId, pnZoneId));
		PrintWriter out = response.getWriter();
		
		db.close();
		out.print(jsonObject.toJSONString());
		
	}
    

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	  	processRequest(request, response);
	
	}

}
